package com.ml.mall.api.ipay;

import com.ml.mall.bean.req.ipay.Ipay88CallBackDto;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.service.ipay.Ipay88Service;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;

/**
 * @description description
 * @author yx
 * @date 2021/9/22
 * @version 1.0
*/
@Api("【order】支付回调")
@RestController
@Slf4j
@RequestMapping("/ipay88")
public class Ipay88Controller {
    @Value("${dns.front_url}")
    private String frontUrl;

    @Autowired
    private Ipay88Service ipay88Service;

    private String paymentSuccessfulUrl = "https://www.baidu.com/";
    private String paymentFailedUrl = "https://www.sogou.com/";

    @PostMapping("/callback")
    public String ipay88CallBack(@Valid Ipay88CallBackDto dto) throws NoSuchAlgorithmException {
        log.info("callback====={}", dto);
        ipay88Service.receiveCallBack(dto);
        return "RECEIVEOK";
    }

    @PostMapping("/response_url")
    public void ipay88ReposenUrl(@Valid Ipay88CallBackDto dto, HttpServletResponse response) throws Exception{
        log.info("reposenUrl====={}",dto);
        ipay88Service.receiveCallBack(dto);
        //根据支付状态进行跳转
        String redirectUrl = "";
        //TODO: 支付成功和失败后的跳转地址暂时设置为baidu和sogou,跳转页面确定后再写入配置文件
        switch (dto.getStatus()){
            case CommonConsts.IPAY88_PAYMENT_FAILED: redirectUrl = paymentFailedUrl; break;
            case CommonConsts.IPAY88_PAYMENT_SUCCESSFUL: redirectUrl = paymentSuccessfulUrl; break;
        }
        log.info("redirectTo====={}", redirectUrl);
        response.sendRedirect(redirectUrl);
    }
}
